package ua.naiksoftware.stomp.pathmatcher;

import ua.naiksoftware.stomp.dto.StompHeader;
import ua.naiksoftware.stomp.dto.StompMessage;

import java.util.ArrayList;

/**
 * RabbitPathMatcher
 *
 * @since 2021-04-27
 */
public class RabbitPathMatcher implements PathMatcher {
    /**
     * RMQ-style wildcards.RabbitPathMatcher
     * See more info <a href="https://www.rabbitmq
     *
     * @param path path
     * @param msg  msg
     * @return boolean
     */
    @Override
    public boolean matches(String path, StompMessage msg) {
        String dest = msg.findHeader(StompHeader.DESTINATION);
        if (dest == null) {
            return false;
        }
        /**
         * for example string "lorem.ipsum.*.sit":
         * split it up into ["lorem", "ipsum", "*", "sit"]
         */
        String[] split = path.split("\\.");
        ArrayList<String> transformed = new ArrayList<>();
        /**
         * check for wildcards and replace with corresponding regex
         */
        for (String string : split) {
            switch (string) {
                case "*":
                    transformed.add("[^.]+");
                    break;
                case "#":
                    /**
                     * e.g. "lorem.#.dolor" should ideally match "lorem.dolor"
                     */
                    transformed.add(".*");
                    break;
                default:
                    transformed.add(string.replaceAll("\\*", ".*"));
                    break;
            }
        }
        /**
         * at this point, 'transformed' looks like ["lorem", "ipsum", "[^.]+", "sit"]
         */
        StringBuilder sb = new StringBuilder();
        for (String string : transformed) {
            if (sb.length() > 0) {
                sb.append("\\.");
            }
            sb.append(string);
        }
        String join = sb.toString();
        return dest.matches(join);
    }
}
